<template>

  <div class="aging">
    
    <!-- 日历bar -->
    <div class="aging_time" @click.stop="selectDate">
      {{ selectorDateShowText }}
    </div>

    <scroller :on-refresh="refresh" style="padding-top: 40px; border-top: 7px solid #f2f2f2;" :style="{background: agingNull ? '#f2f2f2' : '#fff'}">

      <!-- 区显示 店不显示 -->
      <div class="aging_tab" v-if="agingList.length > 1 && firstStoreStatus">
        <p class="tab" v-for="(item, index) in agingList" :class="{active: index === tabIdx}" @click.stop="switchTab(index)">{{ item.storeTypeTabName }}</p>
      </div>

      <div v-if="agingNull">

        <!-- 区显示 店不显示 -->
        <p class="aging_num" v-if="orderList.moduleTitle !== 'undefined' || orderList.moduleTitle !== ''">{{ orderList.moduleTitle }}</p>
    
        <!-- 区 店 订单数据 -->
        <div class="aging_data">
          <div class="data" v-for="(item, index) in orderList.dataList" @click.stop="redirect('timeout_order', item.targetUrl)">
            <p class="title">{{ item.title }}</p>
            <p>{{ item.data }}</p>
            <p class="info_icon" v-if="item.targetUrl">
              <span class="arrow-left"></span>
              <span class="icon"></span>
            </p>
          </div>
        </div>

        <!-- 区 比例数据 -->
        <div class="pres_single_table" v-if="agingList.length > 1">
          <ul v-for="(item, index) in areaRateList.dataList">
            <li v-for="(cItem, idx) in item.groupDataList" @click.stop="redirect('unusual_store', cItem.targetUrl)">
              <!-- <router-link :to="{name: 'unusual_store', query: {typeCode: typeCode, areaCode: areaCode, areaName: areaName, dataType: index, rangType: idx > 1 ? 1 : 0, date: dateYear}}"> -->
                <p class="single_name">
                  {{ cItem.title }}
                  <span class ="dotted_line"></span>
                  <span class="dotted_top_line"></span>
                </p>
                <p class="single_info">
                  {{ cItem.data }}
                  <span class="icon_info" v-if="cItem.targetUrl"><i class="arrow-right"></i></span>
                </p>
              <!-- </router-link> -->
            </li>
          </ul>
        </div>
    
        <!-- 店 比例数据 <span class="company">单</span> -->
        <div class="pres_table" v-else>
          <ul v-for="(item, index) in storeRateList.dataList" :class="{pres_table_one: index === 0}">
            <li v-for="(cItem, idx) in item.groupDataList" @click.stop="redirect('timeout_order', cItem.targetUrl)">
              <!-- <router-link :to="{name: 'timeout_order', query: {typeCode: typeCode, storeCode: areaCode, areaName: areaName, dataType: index, rangType: idx > 1 ? 1 : 0, date: dateYear}}"> -->
                <p class="pres_name">{{ cItem.title }}</p>
                <p class="pres_info">{{ cItem.data }}</p>
                <p class="info_icon" v-if="cItem.targetUrl">
                  <span class="arrow-left"></span>
                  <span class="icon"></span>
                </p>
              <!-- </router-link> -->
            </li>
          </ul>
        </div>
        
        <!-- 区店 历史数据 趋势图 -->
        <div class="charts" v-show="!isChartShow">
          <div id="chart"></div>
          <div class="legend_chart">
            <template v-for="(item, index) in echartsOptions.series">
              <template v-for="(v, i) in echartsOptions.color">
                <span class="legend" :class="{active: optInit[index]}" @click.stop="legendEvt(index)" v-if="index === i"><b :style="{background: v}"></b>{{item.name}}</span>
              </template>
            </template>
          </div>
        </div>
        
        <!-- 区店 耗时数据 -->
        <div class="aging_data">
          <div class="data" v-for="(item, index) in usedTimeList.dataList">
            <p class="title">{{ item.title }}</p>
            <p>{{ item.data }}</p>
          </div>
        </div>

        <!-- 区店 数量数据 -->
        <div class="aging_data">
          <div class="data" v-for="(item, index) in perSingleList.dataList">
            <p class="title">{{ item.title }}</p>
            <p>{{ item.data }}</p>
          </div>
        </div>

      </div>

      <!-- tab切换无数据时 -->
      <div class="nofind" v-else>
        <div class="nofind_pic">
          <img src="../assets/images/no_findgoods.png" >
        </div>
        <p>非淘鲜达店的履约时效分析暂未上线</br>敬请期待</p>
      </div>

    </scroller>

    <!-- 日历组件 -->
    <inpage-calendar v-if="isShowCalendar"
      :disabledStep=0
      calendarType="date-single"
      @on-calendar-selected="handleCalendarSelected($event); initData(tabIdx)"
      @on-calendar-cancel="handleCalendarCancel"/>

  </div>

</template>

<style lang="less" scoped>
  @import "../less/aging/aging.main.less";
 
</style>

<script type="text/ecmascript-6">
import echarts from 'echarts'
import fecha from 'fecha'
import Cookie from 'js-cookie'
import AGING from '@/services/aging'
import inpageCalendar from '@/components/calendar/inpage-calendar'
let selectedIndex = 30
export default {
  name: 'aging',
  components: { inpageCalendar },
  props: {
    customDefine: String
  },
  data() {
    return {
      // 同步big_area 大区 small_area 小区 store 门店
      typeCode: '', 
      // 同步区域编码
      areaCode: '', 
      // 同步区域名称
      areaName: '', 
      // 是否调起日历
      isShowCalendar: false, 
      // 一进来显示特定格式日期展示
      selectorDateShowText: this.timeShowFormat(this.customDefine), 
      // 区下面当前选中tab索引
      tabIdx: 0,
      // 区和店区分 response返回的content长度
      contLength: 1,
      // 无淘鲜达门店时无需分TAB页
      firstStoreStatus: false,
      // 页面数据源
      agingList: [],
      // 是否为空数据
      agingNull: true,
      // 页面订单区块数据
      orderList: Object,
      // 页面区下比例区块数据
      areaRateList: Object,
      // 页面门店下比例区块数据
      storeRateList: Object,
      // 页面时间区块数据
      usedTimeList: Object,
      // 页面数量区块数据
      perSingleList: Object,
      // 是否为唯一门店
      isOnlyStoreArea: 0,
      // 趋势图原数据长度
      trendListLen: 31,
      // 是否显示趋势图
      isChartShow: true,
      // 前端判断开始时间
      startDate: '',
      // 每条折线公用配置
      seriesOpt: {
        type: 'line',
        symbol: 'circle',
        symbolSize: 2,
        showSymbol: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        connectNulls: true
      },
      // 每条折线公用配置
      markLine: {
        lineStyle: {
          color: 'red',
          type: 'dotted'
        },
        animation: false,
        symbolSize: 0,
        label: {
          show: true,
          position: 'middle',
          formatter: '{b}'
        },
        data: []
      },
      // echart整体配置
      echartsOptions: {
        title: { 
          show: false
        },
        color: ['#FF6666', '#F5A623', '#50E3C2', '#7ED321', '#BD10E0', '#2B99F1'],
        backgroundColor: '#fff',
        legend: {
          show: false,
          selected: {}
        },
        tooltip: {
          trigger: 'axis',
          triggerOn: 'click',
          borderRadius: 5,
          backgroundColor: 'rgba(0,0,0,0.8)',
          padding: 5,
          textStyle: {
            fontSize: 12
          },
          position(pos, params, dom, rect, size) {
            // 首先判断鼠标X坐标就是left与画布一半距离比较 显示在左方还是右方
            // 在判断dom内容宽度加个固定值5与鼠标X坐标比较 正常显示还是超出置left为0显示
            // 特殊情况是 初始化显示时 dom内容宽度高度为0 用固定值代替
            let obj = {top: 25}
            if (pos[0] > size.viewSize[0] / 2) {
              if (!size.contentSize[0]) {
                obj.left = pos[0] - 150
              } else {
                if (pos[0] > size.contentSize[0] + 5) {
                  obj.left = pos[0] - size.contentSize[0] - 5
                } else {
                  obj.left = 0
                }
              }
            } else {
              if (size.viewSize[0] - pos[0] > size.contentSize[0] + 5) {
                obj.left = pos[0] + 5
              } else {
                obj.left = size.viewSize[0] - size.contentSize[0]
              }
            }
            return obj
          },
          formatter(obj) {
            selectedIndex = obj[0].dataIndex
            let str = '', xt = '<span style="line-height: 24px">' + obj[0].axisValue + '</span><br/>'
            obj.map((v, i) => {
              str += '<span style="line-height: 20px">' + v.seriesName + '</span>：<span style="color:' + v.color + '">' + v.value + '%</span><br/>'
            })
            return xt + str
          }
        },
        grid: {
          show: true,
          left: '5%',
          right: '5%',
          top: 15,
          bottom: 10,
          containLabel: true,
          backgroundColor: '#fff',
          borderColor: '#ccc',
          borderWidth: 1
        },
        xAxis: {
          show: true,
          type: 'category',
          boundaryGap: false,
          axisLine: {
              show: true,
              lineStyle: {
                color: '#cfcfcf'
              }
          },
          axisTick: {
              show: false,
              length: 3
          },
          axisLabel: {
            interval: 5,
            color: '#666',
            formatter(value, index) {
              return value.split('-')[1] + '/' + value.split('-')[2]
            }
          },
          data: []
        },
        yAxis: {
          show: true,
          splitNumber: 5,
          min: 0,
          max: 120,
          nameTextStyle: {
            color: '#333'
          },
          axisLine: {
              show: true,
              lineStyle: {
                color: '#e5e5e5'
              }
          },
          axisTick: {
              show: false
          },
          axisLabel: {
              show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#e5e5e5',
              type: 'dotted'
            }
          }
        },
        series: []
      },
      // 前端初始值配置默认显示两条线
      optInit: [true, false, true, false, false]
    }
  },
  created () {
    // 桥接设置标题 及时展示
    bridge.setTitle('履约时效分析')
  },
  mounted() {
    // 初始化执行
    this.initData(this.tabIdx)
    // document.addEventListener('click', function() {
    //   window.myChart && window.myChart.dispatchAction({
    //     type: 'hideTip'
    //   })
    // }, false)
  },
  methods: {
    // 图表初始化
    echartsInit() {
      let chart = document.getElementById('chart')

      chart.style.width = window.innerWidth + 'px'
      chart.style.height = '320px'

      let myChart = echarts.init(chart)

      // myChart.showLoading({
      //     text : '数据获取中',
      //     effect: 'bubble'
      // })
      // console.log('图表准备加载配置项')
      myChart.setOption(this.echartsOptions)
      // console.log('图表开始初始化')
      // myChart.hideLoading()

      // 趋势图初始化显示tooltip
      myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: 2,    
          dataIndex: 30
      })

      // myChart.on('click', function (params) {
      //     console.log(params)
      // })

      window.myChart = myChart
    },
    // 调起日历方法
    selectDate() {
      this.isShowCalendar = true
    },
    // 选择选中日期方法
    handleCalendarSelected(value) {
      this.selectorDateShowText = this.timeShowFormat(value)
      this.handleCalendarCancel(false)
    },
    // 关闭日历
    handleCalendarCancel(flag) {
      this.isShowCalendar = flag
    },
    // 初始化格式化日期 同时拿到一个全局年月日日期 作为接口入参
    timeShowFormat(time) {
      // 选中日期时及到子页面后返回按钮过来首页
      if (time) {
        this.dateYear = `${fecha.format(new Date(fecha.parse(time, 'YYYY-MM-DD')), 'YYYY-MM-DD')}`
        return `${fecha.format(new Date(fecha.parse(time, 'YYYY-M-D')), 'M月D日')}`
      } else {
        // 子页面点击链接过来首页
        if (typeof this.$route.query.date !== 'undefined') {
          this.dateYear = this.$route.query.date
          return `${fecha.format(new Date(fecha.parse(this.$route.query.date, 'YYYY-M-D')), 'M月D日')}`
        } else {
          // 从app入口进来 昨天 或者 今天
          const dayValue = 1000 * 60 * 60 * 24
          const today = new Date().valueOf()
          let dateType = typeof this.$route.query.dateType !== 'undefined' ? this.$route.query.dateType : ''
          switch (dateType) {
            case 'TODAY':
              this.dateYear = `${fecha.format(today, 'YYYY-MM-DD')}`
              return `${fecha.format(today, 'M月D日')} 今日`
              break;
            case 'YESTERDAY':
              this.dateYear = `${fecha.format(today - dayValue, 'YYYY-MM-DD')}`
              return `${fecha.format(today - dayValue, 'M月D日')} 昨日`
              break;
            default:
              this.dateYear = `${fecha.format(today, 'YYYY-MM-DD')}`
              return `${fecha.format(today, 'M月D日')} 今日`
          }
        }
      }
    },
    // 区下面切换tab
    switchTab(index) {
      this.tabIdx = index
      this.initData(this.tabIdx)
    },
    // 初始化方法
    initData(idx) {
      // 请求前加载动画
      CommonUtil.indicator.open()
      // 桥接cookies方法
      bridge.getCookies((cookies) => {
        console.log(cookies)
        // 子页面点击路由链接进来 拿到基本信息
        if (typeof this.$route.query.storeCode !== 'undefined') {
          this.typeCode = 'store'
          this.areaCode = this.$route.query.storeCode
          this.areaName = this.$route.query.storeName
          this.isOnlyStoreArea = 1
          // 子页面点击返回按钮进来 超时订单返回
          this.storageFun('storeCode')
        } else {
          // 从app入口进来 拿到基本信息
          this.typeCode = this.typeCode || cookies.dz_area_type
          this.areaCode = this.areaCode || cookies.dz_area_code
          this.areaName = this.areaName || cookies.dz_area_name
          // 子页面点击返回按钮进来 异常门店返回
          this.storageFun('areaCode')
          // 子页面点击返回按钮进来 超时订单返回
          this.storageFun('storeCode')
        }

        // 判断是否显示趋势图
        if (!this.isToday()) {

          // 趋势图x轴坐标序列
          this.curDateHistory(this.dateYear)

        }

        // console.log(this.startDate)

        // 执行接口请求
        this.interfaceData(cookies.dz_auth_token, {
          typeCode: this.typeCode,
          areaCode: this.areaCode,
          date: this.dateYear
        }, idx)

        // 地区选择按钮展示 并附有操作
        this.setAreaSelect(cookies.dz_auth_token, idx)

      })
    },
    // app返回记录值并清除
    storageFun(key) {
      if (Cookie.get(key)) {
        this.typeCode = Cookie.get('typeCode')
        this.areaCode = Cookie.get(key)
        this.areaName = Cookie.get('areaName')
        this.selectorDateShowText = this.timeShowFormat(Cookie.get('date'))
        setTimeout(() => {
          Cookie.remove('date')
          Cookie.remove('typeCode')
          Cookie.remove(key)
          Cookie.remove('areaName')
        }, 1000)
      }
    },
    // 接口操作方法
    interfaceData(token, body, idx) {
      AGING.getAgingData(token, body).then(({data}) => {
        // 请求完关闭动画
        CommonUtil.indicator.close()
        console.log(data)
        // 成功之后操作
        if (data.errorCode === 0) {
          this.agingList = data.body.dataList
          if (data.body.dataList[0].content !== null && data.body.dataList[0].content.length) {
            this.firstStoreStatus = true
          } else {
            this.firstStoreStatus = false
          }
          this.contLength = data.body.dataList.length
          if (data.body.dataList[idx].content !== null && data.body.dataList[idx].content.length) {
            this.agingNull = true
            this.orderList = data.body.dataList[idx].content[0]
            // 区店区分
            if (this.contLength > 1) {
              this.areaRateList = data.body.dataList[idx].content[1]
            } else {
              this.storeRateList = data.body.dataList[idx].content[1]
            }
            this.usedTimeList = data.body.dataList[idx].content[2]
            this.perSingleList = data.body.dataList[idx].content[3]

            // 判断是否显示趋势图
            if (!this.isToday()) {

              window.myChart && window.myChart.dispatchAction({
                type: 'hideTip'
              })

              this.optInit = [true, false, true, false, false]

              // 趋势图接口数据 图例名称 及 具体数值
              this.getTrendChart(token, {
                typeCode: body.typeCode,
                areaCode: body.areaCode,
                businessType: 4,
                startDate: this.startDate,
                endDate: this.dateYear,
                dateType: 'OTHER'
              }, idx)

            }

          } else {
            this.agingNull = false
            this.isChartShow = true
          }
        } else {
          CommonUtil.toast(data.errorDesc || CommonUtil.interfaceTip)
        }
      })
    },
    // 桥接地区选择下拉选择
    setAreaSelect(token, idx) {
      let selectAreaParams = {
        areaType: this.typeCode,
        areaCode: this.areaCode,
        areaName: this.areaName
      }
      selectAreaParams = this.isOnlyStoreArea ? Object.assign(selectAreaParams, {isOnlyStoreArea: this.isOnlyStoreArea}) : selectAreaParams
      bridge.setAreaSelect(selectAreaParams, (res) => {
        this.typeCode = res.areaType
        this.areaCode = res.areaCode
        this.areaName = res.areaName
        this.interfaceData(token, {
          typeCode: this.typeCode,
          areaCode: this.areaCode,
          date: this.dateYear
        }, idx)
      })
    },
    // 当前日期下之前三十天日期
    curDateHistory(date) {
      let curTime = new Date(date).getTime(), dayTime = 24 * 3600 * 1000 
      this.echartsOptions.xAxis.data = []
      for (let i = this.trendListLen; i > 0; i--) {
        let dateChange = new Date(curTime - (i - 1) * dayTime),
            year = dateChange.getFullYear(),
            month = (dateChange.getMonth() + 1 < 10 ? '0' + (dateChange.getMonth() + 1) : dateChange.getMonth() + 1),
            day = dateChange.getDate() < 10 ? '0' + dateChange.getDate() : dateChange.getDate()
        if (i === this.trendListLen) {
          this.startDate = year + '-' + month  + '-'+ day
        }
        this.echartsOptions.xAxis.data.push(year + '-' + month  + '-'+ day)
      }
      // console.log(this.startDate)
    },
    // 格式化日期 无需时分秒 
    dateFormat(date) {
      date = new Date(date.getTime())
      let year = date.getFullYear() + '-',
          month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
          day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      return year + month + day
    },
    // 用于判断是不是今日
    isToday() {
      this.isChartShow = this.dateFormat(new Date()) === this.dateFormat(new Date(this.dateYear))
      return this.dateFormat(new Date()) === this.dateFormat(new Date(this.dateYear))
    },
    // 初始化显示哪些折线图
    initShowLine() {
      let obj = {}
      this.echartsOptions.series.map((item, index) => {
        this.optInit.map((v, i) => {
          if (i === index) {
            obj[item.name] = v
          }
        })
      })
      this.echartsOptions.legend.selected = obj
    },
    // 重构series
    initSeries() {
      let arr = []
      this.echartsOptions.series.map((item, index) => {
        arr.push(Object.assign({}, this.seriesOpt, item))
      })
      this.echartsOptions.series = arr
    },
    // 趋势图接口方法
    getTrendChart(token, body, idx) {
      AGING.getTrendChartData(token, body).then(({data}) => {
        // 请求完关闭动画
        CommonUtil.indicator.close()
        console.log(data)
        // 成功之后操作
        if (data.errorCode === 0) {
          let series = []
          data.body.trendList.map((item, index) => {
            let obj = {}, objData = [], objRate = item.threshold
            obj.name = item.trendName
            obj.markLine = Object.assign({}, this.markLine, {data: [{yAxis: objRate.split(',')[1], name: objRate.split(',')[0]}]})
            if (item.trendData.length < this.trendListLen) {
              this.echartsOptions.xAxis.data.map((vx, ix) => {
                objData.push('0.00')
                item.trendData.map((v, i) => {
                  if (vx === v.date) {
                    objData[ix] = v.value
                  }
                })
              })
            } else {
              item.trendData.map((v, i) => {
                objData.push(v.value)
              })
            }
            // console.log(objData)
            obj.data = objData
            series.push(obj)      
          })
          // 重构接口数据
          this.echartsOptions.series = series

          // 初始化显示哪些折线图
          this.initShowLine()

          // 合并其他选项
          this.initSeries()

          // console.log('图表准备初始化')
          // 趋势图初始化
          this.echartsInit()
          // console.log('图表初始化结束')

        } else {
          CommonUtil.toast(data.errorDesc || CommonUtil.interfaceTip)
        }
      })
    },
    // 下拉刷新方法
    refresh(done) {
      setTimeout(() => {
        this.initData(this.tabIdx)
        done()
      }, 1500)
    },
    // 跳转子页面方法
    redirect(urlName, appStr) {
      if (!appStr || !appStr.indexOf('&')) return
      let keyType = urlName === 'unusual_store' ? 'areaCode' : 'storeCode'
      window.location = window.location.protocol + '//' + location.host + appStr + '&typeCode=' + this.typeCode + '&' + keyType + '=' + this.areaCode + '&areaName=' + this.areaName + '&date=' + this.dateYear
    },
    // 图例外部事件
    legendEvt(idx) {
      window.myChart.dispatchAction({
        type: 'hideTip'
      })
      // this.echartsOptions = Object.assign({}, this.echartsOptions, {animation: true})
      this.echartsOptions.series.map((item, index) => {
        if (index === idx) {
          this.optInit[idx] = !this.optInit[idx]
          this.optInit.splice(idx, 1, this.optInit[idx])
          this.echartsOptions.legend.selected[item.name] = !this.echartsOptions.legend.selected[item.name]
          window.myChart.dispatchAction({
            type: 'legendToggleSelect',
            name: item.name
          })
          window.myChart.dispatchAction({
            type: 'showTip',
            seriesIndex: 2, 
            dataIndex: selectedIndex
          })
        }
      })
    }
  },
  computed: {
    iosAndroid() {
      return bridge.iosAndroid() ? {position: '-webkit-sticky', position: 'sticky'} : {position: 'fixed'}
    }
  },
  // 监听日期实时变更
  watch: {
    customDefine(value) {
      this.selectorDateShowText = this.timeShowFormat(value);
    }
  }
}
</script>
